package com.rtsapp.agent.handler;

import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.utils.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取指定目录所有文件
 *
 * @author liwang
 */
class FileUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger( FileUtil.class );

    /**
     * 递归读取指定目录中的所有文件
     *
     * @param filepath
     * @return
     */
    public static List<File> readFileRecursively( String filepath ) {
        List<File> list = new ArrayList<File>( );
        File file = new File( filepath );
        if ( !file.isDirectory( ) ) {
            list.add( file );
        } else if ( file.isDirectory( ) ) {
            String[] filelist = file.list( );
            for ( int i = 0; i < filelist.length; i++ ) {
                File readfile = new File( filepath + File.separator
                        + filelist[ i ] );
                if ( !readfile.isDirectory( ) ) {
                    list.add( readfile );
                } else if ( readfile.isDirectory( ) ) {
                    list.addAll( readFileRecursively( filepath + File.separator
                            + filelist[ i ] ) );
                }
            }
        }
        return list;
    }

    /**
     * 读取指定目录中的所有文件, 不包含子文件夹内的文件
     *
     * @param dirPath
     * @return ArrayList
     */
    public static List<File> readFile( String dirPath ) {
        if ( StringUtils.isEmpty( dirPath ) ) {
            return null;
        }

        File dir = new File( dirPath );
        if ( !dir.exists( ) || !dir.isDirectory( ) ) {
            LOGGER.error( "hotfix:  {} 不是目录!" );
            return null;
        }

        File[] files = dir.listFiles( );
        if ( files == null && files.length <= 0 ) {
            return null;
        }

        List<File> resultList = new ArrayList<>( );
        File file;
        for ( int i = 0; i < files.length; i++ ) {
            if ( !( file = files[ i ] ).isDirectory( ) ) {
                resultList.add( file );
            }
        }

        return resultList;
    }

    /**
     * 读取文件的二进制数据
     *
     * @param fileName
     * @return
     */
    public static byte[] getBytesFromFile( String fileName ) {
        InputStream is = null;
        try {
            File file = new File( fileName );
            is = new FileInputStream( file );
            long length = file.length( );
            byte[] bytes = new byte[ ( int ) length ];

            int offset = 0;
            int numRead = 0;
            while ( offset < bytes.length
                    && ( numRead = is.read( bytes, offset, bytes.length - offset ) ) >= 0 ) {
                offset += numRead;
            }

            if ( offset < bytes.length ) {
                throw new IOException( "Could not completely read file "
                        + file.getName( ) );
            }
            return bytes;
        } catch ( Exception e ) {
//			logger.error("read file error", e);
            return null;
        } finally {
            if ( is != null ) {
                try {
                    is.close( );
                } catch ( IOException e ) {
                }
            }
        }
    }

    /**
     * 删除指定目录的所有文件
     *
     * @param path
     */
    public static void deleteAllFilesOfDir( File path ) {
        if ( !path.exists( ) )
            return;
        if ( path.isFile( ) ) {
            path.delete( );
            return;
        }
        File[] files = path.listFiles( );
        for ( int i = 0; i < files.length; i++ ) {
            deleteAllFilesOfDir( files[ i ] );
        }
        path.delete( );
    }

    public static void deleteAllFiles( File dir ) {
        if ( dir == null || !dir.exists( ) ) {
            return;
        }

        File[] files = dir.listFiles( );
        for ( int i = 0; i < files.length; i++ ) {
            File file = files[ i ];
            if ( file.isFile( ) ) {
                file.delete( );
            }
        }
    }


    /**
     * 将文件移动到指定的path
     *
     * @param file
     * @param targetPath
     */
    public static void moveFile( File file, String targetPath ) {
        LOGGER.debug( "hotfix:  文件 {} 移动到 {}", file.getPath( ), targetPath );
        file.renameTo( new File( targetPath ) );
        file.delete( );
    }
}
